import { createRouter, createWebHistory } from 'vue-router'
import AuthContainer from '../components/AuthContainer.vue'
import ApiExample from '../components/ApiExample.vue'
import VoiceChat from '../components/VoiceChat.vue'
import { authApi } from '../api/index.js'

const routes = [
  {
    path: '/',
    redirect: '/chat'
  },
  {
    path: '/login',
    name: 'Login',
    component: AuthContainer,
    meta: {
      title: '用户登录'
    }
  },
  {
    path: '/register',
    name: 'Register',
    component: AuthContainer,
    meta: {
      title: '用户注册'
    }
  },
  {
    path: '/chat',
    name: 'Chat',
    component: VoiceChat,
    meta: {
      title: '语音聊天',
      requiresAuth: true
    }
  },
  {
    path: '/home',
    name: 'Home',
    component: ApiExample,
    meta: {
      title: '首页',
      requiresAuth: true
    }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  // 设置页面标题
  if (to.meta.title) {
    document.title = `${to.meta.title} - NADS`
  }

  // 检查是否需要登录
  if (to.meta.requiresAuth) {
    const token = localStorage.getItem('token')
    if (!token) {
      // 未登录，重定向到登录页
      next('/login')
      return
    }
    
    // 验证token有效性
    try {
      await authApi.getCurrentUser()
      // token有效，继续访问
    } catch (error) {
      // token无效，清除并重定向到登录页
      localStorage.removeItem('token')
      next('/login')
      return
    }
  }

  // 如果已登录用户访问登录或注册页，重定向到聊天页面
  if ((to.path === '/login' || to.path === '/register')) {
    const token = localStorage.getItem('token')
    if (token) {
      try {
        // 验证token有效性
        await authApi.getCurrentUser()
        // token有效，重定向到聊天页面
        next('/chat')
        return
      } catch (error) {
        // token无效，清除token，允许访问登录页
        localStorage.removeItem('token')
      }
    }
  }

  next()
})

export default router